// WebSocket工具类
import config from './config.js'

let socketTask = null;
let reconnectTimer = null;
let reconnectCount = 0;
const MAX_RECONNECT_COUNT = 5;

export default {
  connect(userId, onMessage, onError) {
    if (socketTask) {
      socketTask.close();
    }

    const wsUrl = `ws://localhost:8080/api/ws-native?userId=${userId}`;
    
    socketTask = uni.connectSocket({
      url: wsUrl,
      success: () => {
        console.log('WebSocket连接成功');
      },
      fail: (err) => {
        console.error('WebSocket连接失败', err);
        if (onError) onError(err);
      }
    });

    socketTask.onOpen(() => {
      console.log('WebSocket已打开');
      reconnectCount = 0;
    });

    socketTask.onMessage((res) => {
      try {
        const data = JSON.parse(res.data);
        if (onMessage) {
          onMessage(data);
        }
      } catch (e) {
        console.error('解析消息失败', e);
      }
    });

    socketTask.onError((err) => {
      console.error('WebSocket错误', err);
      if (onError) onError(err);
      this.reconnect(userId, onMessage, onError);
    });

    socketTask.onClose(() => {
      console.log('WebSocket已关闭');
      this.reconnect(userId, onMessage, onError);
    });

    return socketTask;
  },

  send(message) {
    if (socketTask && socketTask.readyState === 1) {
      socketTask.send({
        data: JSON.stringify(message),
        success: () => {
          console.log('消息发送成功');
        },
        fail: (err) => {
          console.error('消息发送失败', err);
        }
      });
    } else {
      console.error('WebSocket未连接');
    }
  },

  reconnect(userId, onMessage, onError) {
    if (reconnectCount >= MAX_RECONNECT_COUNT) {
      console.error('重连次数已达上限');
      return;
    }

    reconnectTimer = setTimeout(() => {
      reconnectCount++;
      console.log(`尝试重连 ${reconnectCount}/${MAX_RECONNECT_COUNT}`);
      this.connect(userId, onMessage, onError);
    }, 3000);
  },

  close() {
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
    if (socketTask) {
      socketTask.close();
      socketTask = null;
    }
    reconnectCount = 0;
  }
}

